<template>
    <!-- 弹窗组件 -->
    <div class="dialog-box">
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="800">
            <el-form :model="formData" ref="formRef" :rules="rules">
                <template v-if="props.dialogType === 'addSub' || props.dialogType === 'editSub'">
                    <el-form-item label="主仓库">
                        <el-input v-model="parent_name" disabled></el-input>
                    </el-form-item>
                </template>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="仓库名称" prop="name">
                            <el-input v-model="formData.name" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="仓库编号" prop="code">
                            <el-input v-model="formData.code" placeholder="唯一"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="客户站点">
                            <el-input :disabled="formData.type != '2'" suffix-icon="MoreFilled" @click="openSelectCustomersPopup" readonly
                                style="cursor:pointer;" v-model="formData.customer_name"
                                placeholder="请选择客户站点"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="库管人员" prop="manager_name">
                            <el-input suffix-icon="MoreFilled" @click="showManagerDialogFun" readonly
                                style="cursor:pointer;" v-model="formData.manager_name"
                                placeholder="请选择库管人员"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="联系电话 " prop="manager_phone">
                            <el-input v-model="formData.manager_phone" placeholder="请输入" type="number"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="仓库地址" prop="address">
                            <el-input v-model="formData.address" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="仓库类型 " prop="type">
                            <el-select v-model="formData.type" placeholder="请选择">
                                <el-option v-for="item in typeList" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                    <el-col :span="12">
                        <el-form-item label="库存类别 " prop="type_stock">
                            <el-select v-model="formData.type_stock" placeholder="请选择">
                                <el-option v-for="item in typeStockList" :key="item.value" :label="item.label"
                                    :value="item.value"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>

                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item label="城市" prop="city">
                            <el-select  filterable v-model="formData.city" placeholder="请选择">
                                <el-option v-for="item in cityList" :key="item.label" :label="item.label"
                                    :value="item.label"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="备注">
                            <el-input type="textarea" :rows="3" v-model="formData.note" placeholder="请输入"></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" color="#626aef" @click="submitForm">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>

        <SelectManagerDialog ref="outboundManagerRef" @selectPurchasingDirector="handleSelectPurchasingDirector" />
        <SelectCustomers ref="selectCustomersRef" @selectCustomer="handleSelectCustomer" />
    </div>
</template>

<script setup lang="ts">
import { ref, watch, computed, reactive, onMounted } from "vue";
import type { FormInstance, FormRules } from 'element-plus';
import { ElMessage } from 'element-plus';
import api from "@/api";
import SelectCustomers from "./SelectCustomers.vue";//选择客户
import SelectManagerDialog from './SelectManagerDialog.vue';
// 接收父组件传入的值
const props = defineProps({
    dialogVisible: {
        type: Boolean,
        default: false
    },
    dialogType: {
        type: String,
        default: 'add'
    },
    dialogRow: {
        type: Object,
        default: () => ({})
    }
});

const emit = defineEmits(['update:dialogVisible', 'submit']);

const typeList = ref([
    { label: '主仓库/总库', value: 1 },
    { label: '子仓库/分库', value: 2 },
    { label: '虚拟', value: 3 },
    { label: '其他', value: 4 },

]);

const typeStockList = ref([
    { label: '物资', value: 1 },
    { label: '办公', value: 2 },
    { label: '数字', value: 3 },
    { label: '数据', value: 4 },
    { label: '其他', value: 5 },
]);


// 表单ref
const formRef = ref<FormInstance>();

// 表单验证规则
const rules = reactive<FormRules>({
    name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
    code: [{ required: true, message: '请输入仓库编号', trigger: 'blur' }],
    address: [{ required: true, message: '请输入仓库地址', trigger: 'blur' }],
    manager_name: [{ required: true, message: '请输入库管人员', trigger: 'blur' }],
    manager_phone: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
    customer_name: [{ required: true, message: '请选择客户站点', trigger: 'blur' }],
    type: [{ required: true, message: '请选择仓库类型', trigger: 'change' }],
    city: [{ required: true, message: '请选择城市', trigger: 'change' }],
    type_stock: [{ required: true, message: '请选择库存类别', trigger: 'change' }],
});



// 弹窗标题
const dialogTitle = computed(() => {
    const titleMap = {
        add: '新增仓库',
        edit: '编辑仓库',
        addSub: '新增子仓库',
        editSub: '编辑子仓库'
    };
    return titleMap[props.dialogType] || '仓库信息';
});

interface FormData {
    id: string;
    parent_id: number;
    name: string;
    code: string;
    address: string;
    manager_member_id: string;
    manager_name: string;
    manager_phone: string;
    note: string;
    customer_id: string;
    customer_name: string;
    type: number;
    city: string;
    city_code: string;
    type_stock: number;
}


// 表单数据
const formData = reactive<FormData>({
    id: '',
    name: '',
    code: '',
    address: '',
    manager_member_id: '',
    manager_name: '',
    manager_phone: '',
    customer_id: '',
    note: '',
    parent_id: 0,
    customer_name: '',
    type: 1,
    city: '',
    type_stock: 1,
    city_code: '',
});
let parent_name = ref<string>('');
// 监听对话框显示状态
const dialogVisible = computed({
    get: () => props.dialogVisible,
    set: (val) => {
        emit('update:dialogVisible', val);
    }
});

// 监听props变化
watch(() => props.dialogVisible, (newVal) => {
    if (newVal) {
        // 打开弹窗时，初始化表单数据
        initFormData();
    } else {
        //清空表单验证
        formRef.value?.clearValidate();
    }
});

// 初始化表单数据
const initFormData = () => {
    // 清空表单
    Object.keys(formData).forEach(key => {
        formData[key] = '';
    });
    formData.parent_id = 0;
    console.log(formData, 'sxsxsdsd');
    // 如果是编辑模式，填充表单数据
    if (props.dialogType === 'edit' || props.dialogType === 'editSub') {
        Object.keys(props.dialogRow).forEach(key => {
            if (key in formData) {
                formData[key] = props.dialogRow[key];
            }
        });

        // 特殊处理一些字段
        if (props.dialogRow.title) {
            formData.name = props.dialogRow.title;
        }
        parent_name.value = props.dialogRow.parent_name || '';
        console.log(props.dialogRow, 'props.dialogRow');
        formData.id = props.dialogRow.id || '';
    }

    // 如果是添加子仓库，设置父仓库信息
    if (props.dialogType === 'addSub') {
        formData.parent_id = props.dialogRow.parent_id || '';
        parent_name.value = props.dialogRow.parent_name || '';
        
        
    }
    getCityList()
    //
};
interface CityList {
    label: string;
    value: string;
}

const cityList = ref<CityList[]>([]);
const getCityList = async () => {
    let res = await api.publicFun.getCityList(  
    );
    if (res.code == 200) {
       let arrs = res.data
        cityList.value = arrs.map((item: any) => {
         
            return {
                label: item.city,
                value: item.code
            }
        })
      
    }
}

// 提交表单
const submitForm = async () => {
    if (!formRef.value) return;
    try {
        await formRef.value.validate();

        //如果是字库客户必须选择客户站点
        if(formData.type == 2 && !formData.customer_name){
            ElMessage.error('请选择客户站点');
            return;
        }
        
        //获取城市code
        let cityCode = cityList.value.find(item => item.label === formData.city)?.value;
        formData.city_code = cityCode || '';
        // 添加或编辑主仓库
        if (props.dialogType === 'add') {
            const res = await api.product.warehouse_add(formData);
            if (res.code === 200) {
                ElMessage.success('添加成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '添加失败');
            }
        }
        // 编辑主仓库
        else if (props.dialogType === 'edit') {
            const res = await api.product.warehouse_edit({
                ...formData,
            });
            if (res.code === 200) {
                ElMessage.success('更新成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '更新失败');
            }
        }
        // 添加子仓库
        else if (props.dialogType === 'addSub') {
            const res = await api.product.warehouse_add(formData);
            if (res.code === 200) {
                ElMessage.success('添加子仓库成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '添加子仓库失败');
            }
        }
        // 编辑子仓库
        else if (props.dialogType === 'editSub') {
            const res = await api.product.warehouse_edit(formData);
            if (res.code === 200) {
                ElMessage.success('更新子仓库成功');
                dialogVisible.value = false;
                emit('submit');
            } else {
                ElMessage.error(res.msg || '更新子仓库失败');
            }
        }
    } catch (error) {
        console.error('表单提交错误', error);
        ElMessage.error('请检查表单填写是否正确');
    }
};

let selectCustomersRef = ref();
// 选择客户
const openSelectCustomersPopup = (e: any) => {
    selectCustomersRef.value.openLoading();
    e.target.blur();
};

const outboundManagerRef = ref();
const showManagerDialogFun = () => {
    outboundManagerRef.value.openLoading();
}


interface PurchasingDirector {
    id: number;
    name: string;
    mobile: string;
}

// 处理选择采购负责人
const handleSelectPurchasingDirector = (purchasingDirector: PurchasingDirector) => {
    console.log("选择的负责人:", purchasingDirector);
    formData.manager_member_id = String(purchasingDirector.id);
    formData.manager_phone = purchasingDirector.mobile;
    formData.manager_name = purchasingDirector.name;
};


// 处理选择客户
const handleSelectCustomer = (customer: any) => {
    console.log('选择客户:', customer);

    formData.customer_id = customer.id;
    formData.customer_name = customer.name;

    ElMessage.success(`已选择客户：${customer.name}`);
};



</script>

<style lang="scss" scoped>
::v-deep .el-form-item {
    margin-bottom: 10px !important;
}

::v-deep .form-section {
    padding-top: 0px !important;
}

::v-deep .el-form-item__label {
    margin-left: 0px !important;
}

::v-deep .el-form-item__label-wrap {
    margin-left: 0px !important;
}

::v-deep .el-form-item {
    display: block;
}

:deep(.el-dialog) {
    --el-dialog-padding-primary: 0px;
}

:deep(.el-dialog__header) {
    padding: 10px 16px;
    border-bottom: 1px solid #f0f0f0;
    font-weight: bold;
}

:deep(.dialog-footer) {
    padding: 10px 16px;
    border-top: 1px solid #f0f0f0;
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #000;
}

:deep(.el-dialog__body) {
    padding: 20px 10px;
    padding-right: 30px;
}
</style>
